<template>
    <div class="layout-map-container">
        <div id="fpiMapContainer"></div>
    </div>
</template>

<script setup lang="ts">
import config from '@/config'
import { getPublicFile } from '@/utils/tools'
import { useGlobalStore } from '@/store/global'
import MapUtil from '@/utils/map/mapLayerUtil'
import polygon from '@/assets/map/polygon.json'

const globalStore = useGlobalStore()
// 初始化地图
const initMap = async () => {
    let jsonStyle = await fetch(getPublicFile('lib/mapbox/out-img.json')).then(res => res.json())

    window.glMap = new window.mapboxgl.Map({
        container: 'fpiMapContainer',
        ...config.mapInitOptions,
        style: jsonStyle,
        hash: false,
    })
}

// 监听地图加载完成
const addMapLoadedEventFn = () => {
    // window.glMap.on('load', async () => {
    //     globalStore.changeMapLoaded(true)
    // })
    window.glMap.once('style.load', async () => {
        globalStore.changeMapLoaded(true)
        MapUtil._initBoundaries(polygon)
        createMask(polygon.features[0].geometry.coordinates[0])
    })
    window._mapLayerIdArr = []
}

/**
 * 创建遮罩效果
 */
const createMask = (data: any) => {
    // 绘制遮罩层
    MapUtil._addSourceToMap(
        'hz-mask',
        window.turf.polygon([
            [
                [-180, -90],
                [-180, 90],
                [180, 90],
                [180, -90],
                [-180, -90]
                ],
                data
            ])
        )
        if (!window.glMap.getLayer('hz-mask-layer')) {
        // 避免被hideAllLayer隐藏掉
        window.glMap.addLayer(
            {
                id: 'hz-mask-layer',
                type: 'fill',
                source: 'hz-mask',
                layout: { visibility: 'visible' },
                paint: {
                    'fill-color': 'rgba(0, 0, 0, 1)',
                    'fill-opacity': 0.5
                },
                maxzoom: 13.5
            }
        )
    }
}

onMounted(async () => {
    await initMap()
    addMapLoadedEventFn()
})
</script>

<style lang="scss" scoped>
.layout-map-container {
    position: relative;
    width: 100%;
    height: 100vh;

    #fpiMapContainer {
        width: 100%;
        height: 100%;
    }
}
</style>
